/*
 *  Density.c
 *  
 *
 *  Created by Ben on 17/06/09.
 *  Copyright 2009 __MyCompanyName__. All rights reserved.
 *
 Function to calculate density of individuals within grid cells
 Written to feed into R Script for Parasite lag model.
*/

#include <stdio.h>

void density(double *popX, double *popY, int *poppar, int *idens, int *ipar, int *cellsize, int *spaceX, int *spaceY, int *popsize){
	//idens and ipar are vector of zeros to pass back to R
	int i, j, size=*popsize, sx=*spaceX, sy=*spaceY, cs=*cellsize;
	int g=sx/cs*sy/cs; //number of grid cells
	int dens[g], par[g];
	int gridX[size], gridY[size];

	// initialise grid densities and parasites to zero
	for (j=0; j<g; j++){
		dens[j]=0;
		par[j]=0;
	}
	// calculate densities/parasites for each grid
	for (i=0; i<size; i++){
		gridX[i]=popX[i]/cs;
		gridY[i]=popY[i]/cs;
		dens[sx/cs*gridY[i]+gridX[i]]++;
		if (poppar[i]==1) par[sx/cs*gridY[i]+gridX[i]]++;
	}

	// assign densities/parasites back to individuals
	for (i=0; i<size; i++){
		idens[i]=dens[sx/cs*gridY[i]+gridX[i]];
		ipar[i]=par[sx/cs*gridY[i]+gridX[i]];
	}
	return;
}



